import { useState, useEffect, useContext } from "react";
import {
  Box,
  Text,
  Input,
  InputGroup,
  InputLeftElement,
  Tab,
  TabList,
  TabPanel,
  TabPanels,
  Tabs,
  Button,
  useDisclosure,
} from "@chakra-ui/react";
import { SearchIcon } from "@chakra-ui/icons";
import SystemKey from "./KeyEdit/SystemKey";
import OtherKey from "./KeyEdit/OderKey";
import KeyboardKey from "./KeyEdit/KeyboardKey";
import MacroListV2 from "../Macro/MacroListV2";
import CreateMacroList from "../Macro/CreateMacroList";
import { MacroList } from "@/src/types/types.v1";
import { MainContext } from "@/src/providers/MainProvider";
import { AddIcon } from "@/src/icons/AddIcon";
import _ from "lodash";
import { useTranslation } from "@/src/i18n";

const MouseKeyEdit = () => {
  const [showList, setShowList] = useState(false);
  const [input1, setInput1] = useState("");
  const [activeName, setActiveName] = useState("systemKey");
  const [active, setActive] = useState<string | null>(null);
  const [createMacro, setCreateMacro] = useState(false);

  const {
    macro,
    connectedMouse,
    mouseKeys,
    setMouseKeys,
    profile,
    profileIndex,
  } = useContext(MainContext);

  const [createdMacro, setCreatedMacro] = useState<MacroList>();

  const { t } = useTranslation("");

  const saveMacro = (newMacro: MacroList) => {
    if (createdMacro) {
      macro.setMacroList((macroList: MacroList[]) => {
        macroList[macroList.length - 1] = _.cloneDeep(newMacro);
        return _.cloneDeep(macroList);
      });
    } else {
      setCreatedMacro(newMacro);
      macro.setMacroList((macroList: MacroList[]) => [...macroList, newMacro]);
      if (connectedMouse) {
        connectedMouse.setMacro([...macro.macroList, newMacro]);
        const updatedMouseKeys = mouseKeys.map((key) => {
          if (key.type === 0x70) {
            if (key.code1 < macro.macroList.length) {
              return { ...key, code3: macro.macroList[key.code1].type };
            }
          }
          return key;
        });

        setMouseKeys(updatedMouseKeys);
        profile.updateMouseKeys(profileIndex, updatedMouseKeys);
        if (connectedMouse) {
          connectedMouse.setMouseKeys(updatedMouseKeys, profileIndex);
        }
      }
    }
  };

  useEffect(() => {
    // 初始化代码
  }, []);

  const handleTabChange = (name: string) => {
    setActiveName(name);
    setShowList(true);
  };

  const handleKeyClick = (key: string) => {
    setActive(key);
    setShowList(true);
  };

  const handleRestoreKey = (key: string) => {
    console.log(`Restoring key: ${key}`);
  };

  const handleDragStart = (e: React.DragEvent<HTMLDivElement>) => {
    e.dataTransfer.setData("key", e.currentTarget.id);
  };

  const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
  };

  const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
    const draggedKey = e.dataTransfer.getData("key");
    console.log(`Dropped key: ${draggedKey}`);
  };

  return (
    <Box className="h-full">
      <Box className="w-[360px] h-[calc(100vh-180px)] overflow-y-hidden rounded-[12px] bg-[#2b2d31] my-6pb-[11px]">
        {/* <Box className="p-4">
          <InputGroup className="top-6">
            <InputLeftElement
              pointerEvents="none"
              height="48px"
              className="flex items-center"
            >
              <SearchIcon color="gray.500" />
            </InputLeftElement>
            <Input
              value={input1}
              onChange={(e) => setInput1(e.target.value)}
              size="lg"
              placeholder={t("comingSoon")}
              fontSize="13px"
              className="bg-white pl-12"
            />
          </InputGroup>
        </Box> */}
        <Box className="py-10 h-[calc(100vh-400px)]">
          <Tabs variant="unstyled">
            <TabList
              sx={{
                paddingLeft: "16px",
              }}
            >
              {[
                t("systemKey"),
                t("keyboardKey"),
                t("order"),
                t("recordMacro"),
              ].map((label, index) => (
                <Tab
                  key={index}
                  className="p-4 py-2 text-sm font-semibold text-white hover:text-[#428dff] transition duration-200"
                  _selected={{
                    color: "#0066ff",
                    borderBottom: "2px solid #0066ff",
                  }}
                  fontSize="sm"
                  sx={{
                    paddingLeft: "8px",
                    paddingRight: "8px",
                  }}
                >
                  {label}
                </Tab>
              ))}
            </TabList>
            <TabPanels className="text-white">
              <TabPanel>
                <SystemKey />
              </TabPanel>
              <TabPanel>
                <KeyboardKey />
              </TabPanel>
              <TabPanel>
                <OtherKey />
              </TabPanel>
              <TabPanel>
                <Box>
                  <Text className="mb-4 text-sm font-semibold text-white">
                    {t("macroAssignTip")}
                  </Text>
                  <Button
                    onClick={() => {
                      setCreatedMacro(undefined);
                      setCreateMacro(true);
                    }}
                    disabled={macro.macroList.length >= 32}
                    width="full"
                    className="outline-btn"
                  >
                    <AddIcon className="w-5 h-5" />

                    {t("newMacro")}
                  </Button>
                  {createMacro && (
                    <CreateMacroList
                      onClose={() => setCreateMacro(false)}
                      onSave={saveMacro}
                      checkName={(name) => macro.checkName(name)}
                    />
                  )}
                  <Box>
                    <MacroListV2 />
                  </Box>
                </Box>
              </TabPanel>
            </TabPanels>
          </Tabs>
        </Box>
      </Box>
    </Box>
  );
};

export default MouseKeyEdit;
